package com.huabo.interceptor;

import com.huabo.session.DomainModel;
import com.huabo.session.SessionModel;
import com.huabo.session.UserSession;
import com.huabo.utils.AjaxUtils;
import com.huabo.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录验证拦截器
 * Created by Jackie Liu on 2017/7/10.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserSession userSession;
    @Autowired
    private DomainModel domainModel;

    private AntPathMatcher pathMatcher = new AntPathMatcher();
    private String viewPath = "/view/**";
    private String controllerPath = "/web/**";

    private SessionModel getSessionModel(HttpServletRequest request) {
        SessionModel sessionModel = userSession.getSessionModel(request);
        if (sessionModel != null) {
            return sessionModel;
        }
        return null;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI().replaceFirst(request.getContextPath(), "");
        if (!pathMatcher.match(viewPath, uri) && !pathMatcher.match(controllerPath, uri)) {
            return super.preHandle(request, response, handler);
        }

        SessionModel sessionModel = getSessionModel(request);
        if (sessionModel != null) {
            request.setAttribute(Constants.SESSION_MODEL, sessionModel);
            userSession.resetSessionTime(request);
            return true;
        }

        if (uri.startsWith("/view")) {
            response.sendRedirect(domainModel.getWebDomain() + "/time-out.htm");
            //AjaxUtils.ajaxJsonErrorMessage(response, "会话失效，请重新登录");
        } else {
            AjaxUtils.ajaxJsonErrorMessage(response, "会话失效，请重新登录");
        }
        return false;
    }
}
